import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:flutter_app/config/config.dart';
import 'package:flutter_app/models/general_type.dart';
import 'package:flutter_app/scoped_model/city.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/scoped_model_helper.dart';
import 'package:flutter_app/utils/store.dart';
import 'package:flutter_app/widgets/toast_common.dart';

/// @description: 头部搜索栏
class SearchBar extends StatefulWidget {
  final bool? showLocation;
  final bool? showMap;
  final bool? goBack;
  final Function? cancel;
  final GestureTapCallback onTabSearch;
  final ValueChanged<String>? searchSubmit;
  final String? inputValue;
  final String? defalutValue;
  const SearchBar({
    Key? key,
    this.showLocation = false,
    this.goBack = false,
    this.cancel,
    this.showMap = false,
    this.inputValue = '',
    required this.onTabSearch,
    this.searchSubmit,
    this.defalutValue,
  }) : super(key: key);

  @override
  _SearchBarState createState() => _SearchBarState();
}

class _SearchBarState extends State<SearchBar> {
  late TextEditingController _searchValueController;
  late FocusNode _foucus;
// 清除搜索框内容
  String _searchWord = '';
  void _clickCancelIcon() {
    _searchValueController.clear();
    setState(() {
      _searchWord = '';
    });
  }

  late List cityList;
  // 获取城市列表
  _getHotCity() async {
    var res = await DioHttp.of(context).get('/area/city?level=1');
    var resString = json.decode(res.toString());
    var data = resString["body"];
    data.forEach((i) =>
        {i.remove("short"), i.remove("pinyin"), GeneralType.fromJson(i)});
    setState(() {
      cityList = data;
    });
  }

  @override
  void initState() {
    _getHotCity();
    _foucus = FocusNode();
// input框的值
    _searchValueController = TextEditingController(text: widget.inputValue);
    super.initState();
  }

  _saveCity(GeneralType city) async {
    if (city == null) return;
    //存到全局
    ScopedHelperModel.getModel<CityModel>(context).city = city;
    //存到缓存
    var store = await Store.getInstance();
    var cityString = json.encode(city.toJson());
    store.setString(StoreKeys.city, cityString);
  }

  _changeLocation() async {
    var result = await CityPickers.showCitiesSelector(
        context: context,
        theme: ThemeData(primaryColor: Theme.of(context).primaryColor));

    var cityName = result!.cityName;
    if (null == cityName) return;
    var city = Config.availableCity
        .firstWhere((element) => cityName.startsWith(element.name), orElse: () {
      ToastCommon.showToast('该城市暂未开通');
      return GeneralType(
          Config.availableCity.first.name, Config.availableCity.first.id);
    });

    // if (city == null) return;
    _saveCity(city);
  }

  _getCity() async {
    var store = await Store.getInstance();
    var cityString = await store.getString(StoreKeys.city);
    if (cityString == null) return;
    var city = GeneralType.fromJson(json.decode(cityString));
    ScopedHelperModel.getModel<CityModel>(context).city = city;
  }

  @override
  Widget build(BuildContext context) {
    var city = ScopedHelperModel.getModel<CityModel>(context).city;
    // 仅在变量city为null时赋值
    // city ??= Config.availableCity.first;
    _getCity();
    // print({city.name, 'city'});

    return Column(
      children: [
        Row(
          children: [
            if (widget.showLocation == true)
              GestureDetector(
                onTap: () {
                  _changeLocation();
                },
                child: Row(
                  children: [
                    const Icon(
                      Icons.location_on_sharp,
                      color: Colors.grey,
                    ),
                    Text(
                      city.name,
                      style: const TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                          fontSize: 14),
                    ),
                  ],
                ),
              ),
            if (widget.goBack == false)
              const SizedBox(
                width: 10,
              ),
            if (widget.goBack == true)
              Padding(
                child: GestureDetector(
                  child: Icon(
                    Icons.arrow_back_sharp,
                    color: Colors.grey[700],
                  ),
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                ),
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
              ),
            Expanded(
                child: Container(
              height: 40,
              decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(20)),
              child: TextField(
                onChanged: (v) {
                  setState(() {
                    _searchWord = v;
                  });
                },
                controller: _searchValueController,
                focusNode: _foucus,
                textInputAction: TextInputAction.search,
                //! 判断提交与否，是否在搜索页；不是搜索页，失去焦点
                // onTap: () {
                //   if (widget.searchSubmit == null) {
                //     _foucus.unfocus();
                //   }
                //   widget.onTabSearch();
                // },
                onSubmitted: widget.searchSubmit,
                decoration: InputDecoration(
                  prefixIcon: const Icon(Icons.search),
                  suffixIcon: GestureDetector(
                    onTap: _clickCancelIcon,
                    child: Icon(
                      Icons.cancel,
                      color:
                          _searchWord == '' ? Colors.grey[100] : Colors.green,
                    ),
                  ),
                  hintText: '请输入搜索内容',
                  hintStyle: const TextStyle(color: Colors.black26),
                  border: InputBorder.none,
                ),
              ),
            )),
            if (widget.showMap == true)
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: GestureDetector(
                    child: Icon(
                      Icons.pin_drop_outlined,
                      color: Colors.grey[700],
                    ),
                    onTap: () {}),
              )
          ],
        ),
      ],
    );
  }
}
